package com.ezlcp.form.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ezlcp.commons.base.db.BaseService;
import com.ezlcp.commons.base.entity.JsonPageResult;
import com.ezlcp.commons.base.entity.JsonResult;
import com.ezlcp.commons.base.search.QueryFilter;
import com.ezlcp.commons.tool.StringUtils;
import com.ezlcp.commons.utils.ContextUtil;
import com.ezlcp.form.entity.Form;
import com.ezlcp.form.service.FormServiceImpl;
import com.ezlcp.form.web.BaseController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/ezlcp/form/form")
@Tag(name = "表单（主表）定义")
public class FormController extends BaseController<Form> {
    @Resource
    FormServiceImpl formService;

    @Override
    protected void handleFilter(QueryFilter filter) {
        String tenantId = ContextUtil.getCurrentTenantId();
        if (StringUtils.isNotEmpty(tenantId)) {
            filter.addQueryParam("Q_f.tenant_id_S_EQ", tenantId);
        }
    }

    @Operation(summary = "从实体创建表单")
    @PostMapping("/createFromEntity")
    public JsonResult createFromEntity(@RequestBody Form form) {
        if (form == null || StringUtils.isEmpty(form.getEntId()) || StringUtils.isEmpty(form.getModuleId())
                || form.getFmType() == null || form.getFmCols() == null) {
            return JsonResult.Fail("common.paramError");
        }
        return formService.createFromEntity(form.getEntId(), form.getModuleId(), form.getFmType(), form.getFmCols());
    }

    @Operation(summary = "修改表单")
    @PostMapping("/saveForm")
    public JsonResult saveForm(@RequestBody JSONObject object) {
        var form = object.getObject("form", Form.class);
        String delIds = object.getString("deleteIds");
        if (form == null || form.getControls() == null || form.getControls().isEmpty() || StringUtils.isEmpty(form.getFmId())
                || StringUtils.isEmpty(form.getFmName())) {
            return JsonResult.Fail("common.paramError");
        }
        var oldForm = formService.get(form.getFmId());
        if (oldForm == null || oldForm.getStatus() == 4)
            if (StringUtils.isEmpty(form.getFmId()) || StringUtils.isEmpty(form.getFmName())) {
                return JsonResult.Fail("common.paramError");
            }
        return formService.saveForm(form, delIds);
    }

    @Operation(summary = "设计器中修改表单页面")
    @PostMapping("/editFormJson")
    public JsonResult editFormJson(@RequestBody JSONObject formJson) {
        String formId = formJson.getString(FormServiceImpl.FORM_ID_KEY);
        if (StringUtils.isEmpty(formId)) {
            return JsonResult.Fail("common.paramError");
        }
        var form = formService.getById(formId);
        if (form == null) {
            return JsonResult.Fail("common.paramError");
        }
        var object = formJson.getJSONObject(FormServiceImpl.FORM_JSON_KEY);
        formService.saveFormJson(form, object);
        return JsonResult.Success("common.handleSuccess");
    }

    @Operation(summary = "删除某个表单")
    @PostMapping("/delete")
    public JsonResult delete(@Parameter(description = "主键Id") @RequestParam("pkId") String pkId) {
        if (StringUtils.isEmpty(pkId)) {
            return JsonResult.Fail("common.paramError");
        }
        var form = formService.getById(pkId);
        if (form == null) {
            return JsonResult.Fail("common.paramError");
        }
        return formService.deleteForm(form);
    }

    @Operation(summary = "根据实体列重新生成表单控件（一般用于实体字段修改之后）")
    @PostMapping("/getControlsFromEntity")
    public JsonResult getControlsFromEntity(@Parameter(description = "表单ID") @RequestParam("formId") String formId,
                                            @Parameter(description = "关联实体ID") @RequestParam("entityId") String entityId) {
        if (StringUtils.isEmpty(formId) || StringUtils.isEmpty(entityId)) {
            return JsonResult.Fail("common.paramError");
        }
        return formService.getControlsFromEntity(formId, entityId);
    }

    @Operation(summary = "发布表单或重新发布表单")
    @PostMapping("/publish")
    public JsonResult publish(@Parameter(description = "表单ID") @RequestParam("formId") String formId){
        if (StringUtils.isEmpty(formId) ) {
            return JsonResult.Fail("common.paramError");
        }
        return formService.publish(formId);
    }

    @Override
    public JsonResult save(Form entity, BindingResult validResult) throws Exception {
        return JsonPageResult.getFail("common.apiClose");
    }

    @Override
    public JsonPageResult getAll() {
        return JsonPageResult.getFail("common.apiClose");
    }

    @Override
    public JsonResult del(@RequestParam(value = "id") String id) {
        return JsonResult.Fail("common.apiClose");
    }

    @Override
    public BaseService getBaseService() {
        return formService;
    }

    @Override
    public String getComment() {
        return "表单（主表）定义";
    }
}